package rexsee.service;

import java.sql.Date;
import java.text.SimpleDateFormat;

import rexsee.core.browser.Browser;
import rexsee.core.browser.clazz.JavascriptInterface;
import rexsee.core.browser.clazz.UrlListener;
import rexsee.core.lang.RexseeLanguage;
import rexsee.core.notification.NotificationArgumentsSheet;
import rexsee.core.utilities.Escape;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

public class RexseePushInterface implements JavascriptInterface {

	public static final String INTERFACE_NAME = "Push";
	@Override
	public String getInterfaceName() {
		return (pushBrowser == null) ? null : pushBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return this;
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return new RexseePushInterface(childBrowser);
	}

	public static final String BROWSER_PUSH_ADDRESS = "browser";

	private final Context pushContext;
	private final Browser pushBrowser;
	public RexseePushInterface(Browser browser) {
		pushBrowser = browser;
		pushContext = browser.getContext();
		RexseePush.initDatabase(pushContext);
		if (browser != null) {
			browser.urlListeners.add(new UrlListener("push://") {
				@Override
				public void run(Context context, Browser browser, String url) {
					SQLiteDatabase db = pushContext.openOrCreateDatabase(RexseePush.DATABASE_PUSH, Context.MODE_PRIVATE, null);
					String html = "<HTML><HEAD><TITLE>" + url + "</TITLE></HEAD>";
					html += "<BODY style='margin:0px;background-color:black;color:white;'>";
					if (db != null) {
						try {
							String path = Uri.parse(url).getSchemeSpecificPart();
							if (path == null || path.equals("") || path.substring(path.lastIndexOf("/") + 1).equals("")) {
								html += "<table width=100% cellspacing=0 style='color:white;font-size:16px;'>";
								Cursor cursor = db.rawQuery("SELECT * from " + RexseePush.TABLE_PUSH + ";", null);
								if (cursor.getCount() == 0) {
									html += "<tr><td><div style='padding:10px;line-height:150%;'>Message not found.</div></td></tr>";
								} else {
									for (int i = cursor.getCount() - 1; i >= 0; i--) {
										cursor.moveToPosition(i);
										String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(cursor.getLong(1)));
										NotificationArgumentsSheet argu = (new NotificationArgumentsSheet()).parseArguments(Escape.unescape(cursor.getString(5)));
										html += ((cursor.getInt(3) == RexseePush.PUSH_STATUS_TODO) ? "<tr style='background-color:#444444;'>" : "<tr>");
										html += "<td onclick=\"" + browser.function.getInterfaceName() + ".go('push://" + cursor.getInt(0) + "');\" style='border-bottom:1px solid #222222; padding:10 5 10 5;'>" +
														"<div>" + argu.title + "</div>" +
														"<div style='font-size:14px;color:gray;margin-top:5px;'>[" + cursor.getString(2) + "]&nbsp;" + datetime + "</div>" +
												"</td>";
										html += "</tr>";
									}
								}
								cursor.close();
								html += "</table>";
							} else {
								Long id = Long.parseLong(path.substring(path.lastIndexOf("/") + 1));
								Cursor cursor = db.rawQuery("SELECT * from " + RexseePush.TABLE_PUSH + " where id=" + id + " limit 1;", null);
								if (cursor.getCount() != 1) {
									html += "<BODY style='margin:0px;background-color:black;color:white;'>";
									html += "<div style='padding:10px;line-height:150%;'>Message " + id + " not found.</div>";
								} else {
									cursor.moveToFirst();
									NotificationArgumentsSheet argu = (new NotificationArgumentsSheet()).parseArguments(Escape.unescape(cursor.getString(5)));
									html += "<SCRIPT type=text/javascript>window.onload = function(){" + getInterfaceName() + ".setRead(" + id + ");}</SCRIPT>";
									html += "<BODY style='margin:0px;background-color:black;color:white;'>";
									String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(cursor.getLong(1)));
									html += "<table width=100% height=100% cellspacing=0 cellpadding=0 style='color:white;font-size:18px;'>";
									html += "<tr height=50px>" +
											"<td style='border-bottom:1px solid #222222; padding:10 5 10 5;'>" +
												"<div>" + argu.title + "</div>" +
												"<div style='font-size:14px;color:gray;margin-top:5px;'>[" + cursor.getString(2) + "]&nbsp;" + datetime + "</div>" +
											"</td>" +
											"</tr>";
									html += "<tr><td valign=top style='padding:10px;font-size:16px;'>";
									if (!argu.url.equals("") && !argu.url.equals(url)) {
										html += "<a href='" + argu.url + "' style='color:white;text-decoration:underline;'>" + argu.message + "</a>";
									} else {
										html += argu.message;
									}
									html += "</td></tr>";
									html += "<tr height=35px><td valign=bottom style='border-top:1px solid #222222; padding:10 5 10 5;font-size:16px;'>";
									html += "<a href='" + browser.application.resources.prefix + ":' onclick=\"javascript:" + getInterfaceName() + ".remove(" + cursor.getInt(0) + ");" + browser.function.getInterfaceName() + ".goBack();\" style='color:white;text-decoration:underline;'>" + RexseeLanguage.ACTION_DELETE + "</a>";
									html += "</td></tr>";
									html += "</table>";
								}
								cursor.close();
							}
						} catch (Exception e) {
							db.close();
							html += "<div style='color:white;font-size:16px;padding:10px;'>Database Error: " + e.getLocalizedMessage() + "</div>";
						}
					} else {
						html += "<div style='color:white;font-size:16px;padding:10px;'>Database Error: Can't open database.</div>";
					}
					html += "</BODY>";
					html += "</HTML>";
					db.close();
					browser.function.loadHTMLWithoutHistory(html);
				}
				@Override
				public boolean shouldAddToHistory(Context context, Browser browser, String url) {
					return true;
				}
			});
		}
	}

	//JavaScript Interface
	public String getIds(String type) {
		try {
			SQLiteDatabase db = pushContext.openOrCreateDatabase(RexseePush.DATABASE_PUSH, Context.MODE_PRIVATE, null);
			Cursor cursor;
			if (type == null || type.equals("")) {
				cursor = db.rawQuery("SELECT id from " + RexseePush.TABLE_PUSH + ";", null);
			} else {
				cursor = db.rawQuery("SELECT id from " + RexseePush.TABLE_PUSH + " WHERE type='" + type + "';", null);
			}
			String rtn = "";
			if (cursor != null && cursor.getCount() > 0) {
				for (int i = 0; i < cursor.getCount(); i++) {
					cursor.moveToPosition(i);
					rtn += (i == 0) ? "\"" + cursor.getInt(0) + "\"" : ",\"" + cursor.getInt(0) + "\"";
				}
			}
			try {
				cursor.close();
			} catch (Exception e) {
			}
			db.close();
			return "[" + rtn + "]";
		} catch (Exception e) {
			return "[]";
		}
	}
	public String getIds() {
		return getIds(null);
	}
	public void add(String body) {
		RexseePush.add(pushContext, RexseePush.PUSH_TYPE_BROWSER, System.currentTimeMillis(), BROWSER_PUSH_ADDRESS, body);
	}
	public String get(long id) {
		try {
			SQLiteDatabase db = pushContext.openOrCreateDatabase(RexseePush.DATABASE_PUSH, Context.MODE_PRIVATE, null);
			Cursor cursor = db.rawQuery("SELECT * from " + RexseePush.TABLE_PUSH + " WHERE id=" + id + ";", null);
			String rtn = "{";
			if (cursor != null && cursor.getCount() != 0) {
				cursor.moveToFirst();
				rtn += "\"id\":\"" + cursor.getInt(0) + "\"";
				rtn += ",\"date\":" + cursor.getLong(1) + "";
				rtn += ",\"type\":\"" + cursor.getString(2) + "\"";
				rtn += ",\"done\":" + cursor.getInt(3) + "";
				rtn += ",\"address\":\"" + cursor.getString(4) + "\"";
				rtn += ",\"arguments\":\"" + cursor.getString(5) + "\"";
			}
			rtn += "}";
			try {
				cursor.close();
			} catch (Exception e) {
			}
			db.close();
			return rtn;
		} catch (Exception e) {
			return "";
		}
	}
	public void remove(long id) {
		try {
			SQLiteDatabase db = pushContext.openOrCreateDatabase(RexseePush.DATABASE_PUSH, Context.MODE_PRIVATE, null);
			db.execSQL("DELETE FROM " + RexseePush.TABLE_PUSH + " where id=" + id + ";");
			db.close();
		} catch (Exception e) {
		}
	}
	public void setRead(long id) {
		try {
			SQLiteDatabase db = pushContext.openOrCreateDatabase(RexseePush.DATABASE_PUSH, Context.MODE_PRIVATE, null);
			db.execSQL("UPDATE " + RexseePush.TABLE_PUSH + " SET done=" + RexseePush.PUSH_STATUS_DONE + " where id=" + id + ";");
			db.close();
		} catch (Exception e) {
		}
	}

}
